package com.pb.camera.h264;

import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.VideoView;
import com.pb.camera.utils.TaskHelper;
import com.pb.camera.work.ControlTask;
import com.pb.camera.work.IOTCInit;
import com.pb.camera.work.IOTCInit.InitSuccessCallBack;

public class VedioPlayView extends SurfaceView implements Callback,
		AudioBufferDoneInterface, VideoBufferUpdateInterface, InitSuccessCallBack ,OnTouchListener{
	public static final int VIDEO_LAYOUT_ORIGIN = 0;
	public static final int VIDEO_LAYOUT_SCALE = 1;
	public static final int VIDEO_LAYOUT_STRETCH = 2;
	public static final int VIDEO_LAYOUT_ZOOM = 3;
	public static final int VIDEO_LAYOUT_FIT_PARENT = 4;
	private static final int STATE_ERROR = -1;
	private static final int STATE_IDLE = 0;
	private static final int STATE_PREPARING = 1;
	private static final int STATE_PREPARED = 2;
	private static final int STATE_PLAYING = 3;
	private static final int STATE_PAUSED = 4;
	private static final int STATE_PLAYBACK_COMPLETED = 5;
	private static final int STATE_SUSPEND = 6;
	private static final int STATE_RESUME = 7;
	private static final int STATE_SUSPEND_UNSUPPORTED = 8;
	private static final int LOCK_CANVAS = 9;
	// /////////////////////////////////////////////////////
	private int mWidth = 1280; // 此处设定不同的分辨率
	private int mHeight = 720;
	private SurfaceHolder mSurfaceHolder;
	private IOTCInit mIOTCInit;
	private ExecutorService mDrawexecutor;
	private ExecutorService mBufferWorkExecuotor;
	private ByteBuffer mByteBuffer;
	private Future<?> mDrawFuture;

	private VideoBufferThread mVideoBufferThread;
	private AudioBufferThread mAudioBufferThread;
	private int screenHeight,screenWidth,outScreenWidth;
	private Rect rect;
	private int fX;
	private int viewXcurret;
	private int view2Xcurrent;
	private int viewYcurrent;
	private int view2Ycurrent;
	private boolean initIotcSuccess = false;
	public boolean isFirstPlay = true; 
	private int successAvindex = -1;
	
	
	int model = 0;
	private boolean isFullScreen = false;
	private  boolean isBigView = false;

	public VedioPlayView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public VedioPlayView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public VedioPlayView(Context context) {
		super(context);
		init();
	}


	public VideoBufferThread getmVideoBufferThread() {
		return mVideoBufferThread;
	}
	public ExecutorService getBufferWorkExecuotor() {
		return mBufferWorkExecuotor;
	}
	public AudioBufferThread getmAudioBufferThread() {
		return mAudioBufferThread;
	}

	public void setViewResolutionWithAndHegh(int width,int height){
		this.mWidth = width;
		this.mHeight = height;
	}
	
	public void setFullScreen(boolean isFullScreen){
		this.isFullScreen = isFullScreen;
		if(isFullScreen){
			rect.left = 0;
			rect.top = 0;
			rect.right = screenHeight;
			rect.bottom = screenWidth;
		}else{
			rect.left = viewXcurret;
			rect.right = viewXcurret + screenWidth*4/3;
			rect.top = viewYcurrent;
			rect.bottom = viewYcurrent + screenWidth*3/4;
		}
		isBigView = false;
		myDraw();
	}

	private void init() {
		screenHeight = getResources().getDisplayMetrics().heightPixels;
		screenWidth = getResources().getDisplayMetrics().widthPixels;
		outScreenWidth = screenWidth/3;
		viewXcurret = -screenWidth/6;
		view2Xcurrent = -screenWidth*5/6;
		viewYcurrent = 0;
		view2Ycurrent = -screenWidth*3/8;
		//全屏旋转的时候用,旋转90度
		matrix = new Matrix();
		matrix.setRotate(90);
		srcRect = new Rect();
		rect = new Rect(viewXcurret, viewYcurrent, screenWidth*4/3+viewXcurret, screenWidth*3/4);
		// TODO: 在这里检查摄像头的数据是否正确读取等
		mSurfaceHolder = getHolder();
		mSurfaceHolder.addCallback(this);
		mDrawexecutor = Executors.newSingleThreadExecutor();
		mBufferWorkExecuotor = Executors.newFixedThreadPool(2); // 并行线程 service
		this.setOnTouchListener(this);
	}

	public void setIniter(IOTCInit iOTCInit) {
		assert (iOTCInit != null);
		this.mIOTCInit = iOTCInit;
		mIOTCInit.setOnInitSuccessCallBack(this);
	}
	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		mFramBitmap = Bitmap.createBitmap(getWidth(),
				getHeight(), Bitmap.Config.RGB_565);
	}

//	public void startInitPlayView() {
//		
//		if (mIOTCInit != null)
//			new Thread(new Runnable() {
//				@Override
//				public void run() {
//					mIOTCInit.runInit();
//				}
//			}).start();
//	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {}
	
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		if(mFramBitmap != null && ! mFramBitmap.isRecycled()){
			mFramBitmap.recycle();
		}
	};

	@Override
	public void onVideoBufferUpdate(ByteBuffer byteBuffer) {
			Canvas mCanvas = mSurfaceHolder.lockCanvas();
			byteBuffer.rewind();
			if(mCanvas != null){
//			mFramBitmap = Bitmap.createBitmap(getWidth(),
//					getHeight(), Bitmap.Config.RGB_565);
			if(mFramBitmap.isRecycled()){
				mFramBitmap = Bitmap.createBitmap(getWidth(),
						getHeight(), Bitmap.Config.RGB_565);
				mFramBitmap.copyPixelsFromBuffer(byteBuffer);// makeBuffer(data565,
			}else{
				mFramBitmap.copyPixelsFromBuffer(byteBuffer);// makeBuffer(data565,
			}
			
			srcRect.left = 0;
			srcRect.top = 0;
			srcRect.right = mWidth;
			srcRect.bottom = mHeight;
//			if(isFullScreen){
//				rect.left = 0;
//				rect.top = 0;
//				rect.right = screenHeight;
//				rect.bottom = screenWidth;
//				mCanvas.drawBitmap(mFramBitmap, srcRect, rect, null);
//			}else{
			Log.e("资源文件的宽和高", mWidth+"----"+mHeight);
			//画图是的mFramBitmap 空指针异常
			if(mFramBitmap != null){
				mCanvas.drawBitmap(mFramBitmap, srcRect, rect, null);
			}
//			}
			}
			mSurfaceHolder.unlockCanvasAndPost(mCanvas);
	}
	

	@Override
	public void onAudioBufferUpdate(InputStream audioBuffer) {
	}

	public void myDraw() {
		Canvas mCanvas = mSurfaceHolder.lockCanvas();
		if(mCanvas != null){
//			if(isFullScreen){
//				fullBitmap = Bitmap.createBitmap(mFramBitmap, 0, 0, mWidth, mHeight, matrix, true);
//				rect.left = 0;
//				rect.top = 0;
//				rect.right = screenWidth;
//				rect.bottom = screenHeight;
//				
//				mCanvas.drawBitmap(fullBitmap, null, rect, mPaint);
//			}else{
				srcRect.left = 0;
				srcRect.top = 0;
				srcRect.right = mWidth;
				srcRect.bottom = mHeight;
				
				if(mFramBitmap != null){
					mCanvas.drawBitmap(mFramBitmap, srcRect, rect, null);
				}
//			}
			
			mSurfaceHolder.unlockCanvasAndPost(mCanvas);
		}
	}

	@Override
	public void OnInitSuccess(String mUIdV, int avIndex) {
		Log.e("av初始化结果", "success");
		initIotcSuccess = true;
		successAvindex = avIndex;
		mFramBitmap = Bitmap.createBitmap(getWidth(),
				getHeight(), Bitmap.Config.RGB_565);
		if(isFirstPlay){
			TaskHelper.exec(new Runnable() {
				@Override
				public void run() {
					ControlTask.getEnviroment(successAvindex);
					ControlTask.getVideoMode(successAvindex);
					ControlTask.getResolution(successAvindex);
				}
			});
			isFirstPlay = false;
		}else{
			startThreads();
		}
//		getAvIndexSuccess.getAvIndexSuccess(avIndex);
	}
	
	

	public void startThreads() {
		if(initIotcSuccess && successAvindex != -1){
			if (mVideoBufferThread == null)
				mVideoBufferThread = new VideoBufferThread(successAvindex, this);
			if (mAudioBufferThread == null)
				mAudioBufferThread = new AudioBufferThread(successAvindex);
			if(mBufferWorkExecuotor == null){
				mBufferWorkExecuotor = Executors.newFixedThreadPool(2);
				mBufferWorkExecuotor.execute(mVideoBufferThread);
				mBufferWorkExecuotor.execute(mAudioBufferThread);
			}else{
				mBufferWorkExecuotor.execute(mVideoBufferThread);
				mBufferWorkExecuotor.execute(mAudioBufferThread);
			}
		}
	}

	//切换分辨率
	public void stopPlayView(){
		isFirstPlay = false;
		Log.e("关闭了", "关闭了 ffffffffffff");
		if(mVideoBufferThread != null){
			mVideoBufferThread.isGettingData = false;
			mVideoBufferThread.interrupt();
			mVideoBufferThread = null;
			Log.e("关闭了", "关闭了 ");
		}
		if(mAudioBufferThread != null){
			mAudioBufferThread.isPlayingAudio = false;
			mAudioBufferThread.interrupt();
			mAudioBufferThread = null;
		}
		mBufferWorkExecuotor = null;
//		mIOTCInit.stopClient();
	}
	
	@Override
	protected void onDetachedFromWindow() {
		// TODO Auto-generated method stub
		super.onDetachedFromWindow();
		if (mIOTCInit != null)
			mIOTCInit.stopClient();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		switch (event.getAction()& MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			//点击之前
			model = 1;
			fX = (int) event.getX();
			fY = (int) event.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			int nowX = (int) event.getX();
			int nowY = (int) event.getY();
			int movX = nowX-fX;
			int movY = nowY-fY;
			if(!isFullScreen){
				
			if(model>1){
				float newRate = spacing(event);
				if(isBigView){
					if(newRate < oldRate){
						rect.left = viewXcurret;
						rect.right = viewXcurret + screenWidth*4/3;
						rect.top = viewYcurrent;
						rect.bottom = viewYcurrent + screenWidth*3/4;
						isBigView = false;
					}
				}else{
					//放大的时候,以第一次两个手指的中点为中心放大
					if(newRate > oldRate){
						int midX = (int) middle.x;
						int midY = (int) middle.y;
						
					    int leftCurrent = rect.left;
					    int leftS = midX - leftCurrent;
					    view2Xcurrent = midX - leftS*2;
					    view2Ycurrent = -midY;
					    
						rect.left = view2Xcurrent;
						rect.right = view2Xcurrent + screenWidth*8/3;
						rect.top = view2Ycurrent;
						rect.bottom = view2Ycurrent + screenWidth*3/2;
						isBigView = true;
					}
				}
			}else{
				if(isBigView){
					//往右划
					if(movX > 0 && Math.abs(movX)>30&& view2Xcurrent <= 0 && view2Xcurrent >= -screenWidth*5/3){
						if((movX + view2Xcurrent) > 0){
							view2Xcurrent = 0;
						}else{
							view2Xcurrent = movX +view2Xcurrent;
						}
					}else if(movX < 0 && Math.abs(movX)>30 && view2Xcurrent <=0 && view2Xcurrent >= -screenWidth*5/3){
						//向左边 
						if((movX + view2Xcurrent)< -outScreenWidth){
							view2Xcurrent = -(screenWidth*5/3);
						}else{
							view2Xcurrent = movX + view2Xcurrent;
						}
					}
					
					//往下划
					if(movY > 0 && Math.abs(movY)>30&& view2Ycurrent <= 0 && view2Ycurrent >= -screenWidth*3/4){
						if((movY + view2Ycurrent) > 0){
							view2Ycurrent = 0;
						}else{
							view2Ycurrent = movY +view2Ycurrent;
						}
					}else if(movY < 0 && Math.abs(movY)>30 && view2Ycurrent <=0 && view2Ycurrent >= -screenWidth*3/4){
						//向上边 
	        			if((movY + view2Ycurrent)< -screenWidth*3/4){
	        				view2Ycurrent = -screenWidth*3/4;
						}else{
							view2Ycurrent = movY + view2Ycurrent;
						}
					}
					
					rect.left = view2Xcurrent;
					rect.right = view2Xcurrent + screenWidth*8/3;
					rect.top = view2Ycurrent;
					rect.bottom = view2Ycurrent + screenWidth*3/2;
				}else{
					//往右划
					if(movX > 0 && Math.abs(movX)>30&& viewXcurret <=0 && viewXcurret >= -outScreenWidth){
						if((movX + viewXcurret) > 0){
							viewXcurret = 0;
						}else{
							viewXcurret = movX +viewXcurret;
						}
					}else if(movX < 0 && Math.abs(movX)>30 && viewXcurret <=0 && viewXcurret >= -outScreenWidth){
						//向左边 
	        			if((movX + viewXcurret)< -outScreenWidth){
							viewXcurret = -outScreenWidth;
						}else{
							viewXcurret = movX + viewXcurret;
						}
					}
					rect.left = viewXcurret;
					rect.right = viewXcurret + screenWidth*4/3;
					rect.top = 0;
					rect.bottom = screenWidth*3/4;
				}
			}
			myDraw();
			
			}
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			model+=1;
			if(event.getPointerCount() >1){
				oldRate = spacing(event);
				if(oldRate > 10f){
					middle = middle(event);
				}
			}
			break;
		case MotionEvent.ACTION_POINTER_UP:
			model -= 1;
			break;
		case MotionEvent.ACTION_UP:
			model = 0;
			int upX = (int) event.getX();
			int upY = (int) event.getY();
			int upMoveX = upX-fX;
			int upMoveY = upY-fY;
			if(Math.abs(upMoveX) < 30 && Math.abs(upMoveY)<30){
				singleTapUp.onMySingleTapUp();
			}
			break;

		default:
			break;
		}
		
		return true;
	}
	//计算连个触点之间的距离
	private float spacing(MotionEvent event) {  
        float x = event.getX(0) - event.getX(1);  
        float y = event.getY(0) - event.getY(1);  
        return (float)Math.sqrt(x * x + y * y);
    } 
	// 计算两个触摸点的中点   
    private PointF middle(MotionEvent event) {  
        float x = event.getX(0) + event.getX(1);  
        float y = event.getY(0) + event.getY(1);  
        return new PointF(x / 2, y / 2);  
    }  
	
	SingleTapUp singleTapUp;
	private float oldRate;
	private Rect srcRect;
	private Bitmap mFramBitmap;
	private int fY;
	private PointF middle;
	private Matrix matrix;
	public interface SingleTapUp{
		public void onMySingleTapUp();
	}
	
	public void setOnMySingleTapUp(SingleTapUp singleTapUp){
		this.singleTapUp = singleTapUp;
	}
	
//	private GetAvIndexSuccess getAvIndexSuccess;
//	public interface GetAvIndexSuccess{
//		public void getAvIndexSuccess(int avIndex);
//	}
//	
//	public void setOnGetAvIndexSuccess(GetAvIndexSuccess getAvIndexSuccess){
//		this.getAvIndexSuccess = getAvIndexSuccess;
//	}
	
}